﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;

namespace Pyramid_Game
{
    public abstract class MakePloygon : GameScreen
    {
        /// <summary>
        /// 밑바닥이 되는 도형(다각형)
        /// </summary>
        protected Texture2D polygon;

        /// <summary>
        /// 조각들
        /// </summary>
        protected Texture2D[] piece;

        /// <summary>
        /// 조각들의 사각형 좌표
        /// </summary>
        protected Rectangle[] shape;

        /// <summary>
        /// shape가 들어갈 위치(정답위치)
        /// </summary>
        protected Vector2[] position;

        /// <summary>
        /// 정답위치의 20 pixel 근처면 그 위치에 붙여주는 것
        /// </summary>
        protected int margin = 15;

        /// <summary>
        /// 조각 선택여부
        /// </summary>
        protected bool select = false;

        /// <summary>
        /// 정답체크
        /// </summary>
        protected bool correct = false;

        /// <summary>
        /// 
        /// </summary>
        protected int SelectedPiece = -1;

        /// <summary>
        /// 도형의 위치를 랜덤으로
        /// </summary>
        protected Random rand = new Random();

        /// <summary>
        /// 조각 갯수
        /// </summary>
        protected int size;

        /// <summary>
        /// 도형 depth
        /// </summary>
        protected float[] depth;

        protected float MinDepth = 1;

        protected int cnt = 0;

        public MakePloygon()
        {

        }

        bool IsRegionTransparent(Texture2D texture, Rectangle r)
        {
            if (r.X + r.Width > texture.Width)
            {
                r.Width = texture.Width - r.X;
            }
            if (r.Y + r.Height > texture.Height)
            {
                r.Height = texture.Height - r.Y;
            } 
            
            int size = r.Width * r.Height;
            Color[] buffer = new Color[size];
            
            texture.GetData<Color>(0, r, buffer, 0, size);
            return buffer.All(c => c == Color.Transparent);
        }

        public override void LoadContent(ContentManager content)
        {

        }

        public override void Update(Touch touch, GameTime gameTime)
        {
            cnt = 0;
            //tap했을 때
            TouchCollection touchCollection = TouchPanel.GetState();
            if (SelectedPiece == -1)
            {
                foreach (TouchLocation tl in touchCollection)
                {
                    if (tl.State == TouchLocationState.Pressed)
                    {
                        Vector2 p = tl.Position;
                        float min = 2;
                        for (int i = 0; i < size; i++)
                        {
                            if (shape[i].Contains((int)p.X, (int)p.Y))
                            {
                                //투명한 부분을 선택하지 않은 경우
                                if (!IsRegionTransparent(piece[i],
                                    new Rectangle(Math.Abs((int)p.X - shape[i].X), Math.Abs((int)p.Y - shape[i].Y), 5, 5)))
                                {
                                    //제일 앞에 있는 도형인지 확인 후
                                    if (min > depth[i])
                                    {
                                        min = depth[i];
                                        SelectedPiece = i;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            foreach (GestureSample gesture in touch.Gestures)
            {
                if (gesture.GestureType == GestureType.FreeDrag)
                {
                    if (SelectedPiece != -1)
                    {
                        shape[SelectedPiece].X += (int)gesture.Delta.X;
                        shape[SelectedPiece].Y += (int)gesture.Delta.Y;
                        depth[SelectedPiece] = 0;
                    }
                }

                //drag완료 후 SelectedPiece 초기화
                if (gesture.GestureType == GestureType.DragComplete)
                {
                    if (SelectedPiece != -1)
                    {
                        depth[SelectedPiece] = MinDepth - 0.001f;
                        MinDepth = depth[SelectedPiece];

                        if(Math.Abs(position[SelectedPiece].X - shape[SelectedPiece].X) <= margin
                           && Math.Abs(position[SelectedPiece].Y - shape[SelectedPiece].Y) <= margin)
                        {
                            shape[SelectedPiece].X = (int)position[SelectedPiece].X;
                            shape[SelectedPiece].Y = (int)position[SelectedPiece].Y;
                        }
                    }
                    SelectedPiece = -1;
                }
            }
            for (int i = 0; i < size; i++)
            {
                if (shape[i].X == position[i].X && shape[i].Y == position[i].Y)
                    cnt++;
            }
            if (cnt == size)
            {
                screenManager.RemoveScreen(this);
                screenManager.AddScreen(new resultScreen(0, "MakePloygon"));

                correct = true;
            }

            if (correct)
            {

            }
        }

        public override void Draw(SpriteBatch spriteBatch, GameTime gameTime)
        {
            spriteBatch.End();
            spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
            spriteBatch.Draw(polygon, new Vector2(250, 90), Color.White);
            
            for (int i = 0; i < size; i++)
            {
                spriteBatch.Draw(piece[i],
                    shape[i],
                    new Rectangle(0,0,piece[i].Width,piece[i].Height),
                    Color.White,
                    0.0f,
                    Vector2.Zero,
                    SpriteEffects.None,
                    depth[i]);
            }
            spriteBatch.End();
            spriteBatch.Begin();
        }
        /*
        public enum State
        {
            Active,
            Pause
        }
        
        /// <summary>
        /// 스테이지 상태 값: 초기 스테이지는 Pause
        /// </summary>
        public State state = State.Pause;

        /// <summary>
        /// 밑바닥이 되는 도형(다각형)
        /// </summary>
        protected Texture2D polygon;

        /// <summary>
        /// 도형을 이루는 조각
        /// </summary>
        protected Texture2D[] piece;

        /// <summary>
        /// 20 pixel 근처면 정답일 경우만 맞춰주는 것
        /// </summary>
        protected int margin = 20;

        /// <summary>
        /// 정답 근처에 왔는지를 체크하는 사각형
        /// </summary>
        protected List<Rectangle> judgement = new List<Rectangle>();

        /// <summary>
        /// 조각의 위치 (조각의 왼쪽 맨 윗점)
        /// </summary>
        protected Point[] shape;

        /// <summary>
        /// 정답 조각 위치
        /// </summary>
        protected Vector2[] position;

        /// <summary>
        /// 맞았는지 체크
        /// </summary>
        protected bool correct = false;

        /// <summary>
        /// 선택을 했는지를 체크
        /// </summary>
        protected bool select = false;

        /// <summary>
        /// 
        /// </summary>
        protected int number = 0;

        /// <summary>
        /// 도형의 위치를 랜덤으로
        /// </summary>
        protected Random rand = new Random();

        /// <summary>
        /// 조각 갯수
        /// </summary>
        protected int size;

        

        public MakePloygon()
        {

        }
        */
        /*
        bool IsRegionTransparent(Texture2D texture, Rectangle r)
        {
            int size = r.Width * r.Height;
            Color[] buffer = new Color[size];
            texture.GetData<Color>(0, r, buffer, 0, size);
            return buffer.All(c => c == Color.Transparent);
        }
        
        public override void LoadContent(ContentManager content)
        {

        }
*/
        /*
        public override void Update(Touch touch, GameTime gameTime)
        {
            if (correct)
            {
                foreach (GestureSample gesture in touch.Gestures)
                {
                    if (gesture.GestureType == GestureType.Tap)
                    {
                        // 정답 맞췄다는 그림 추가


                        Point tapLocation = new Point((int)gesture.Position.X, (int)gesture.Position.Y);
                        screenManager.RemoveScreen(this);
                    }
                }
                return;
            }

            if (state == State.Active)
            {
                for (int i = 0; i < size; i++)
                {
                    if (judgement[i].Contains(shape[i]))
                    {
                        shape[i].X = (int)position[i].X;
                        shape[i].Y = (int)position[i].Y;
                    }
                }

                int count = 0;
                for (int i = 0; i < size; i++)
                {
                    if (shape[i].X == (int)position[i].X && shape[i].Y == (int)position[i].Y)
                    {
                        count++;
                    }
                }
                if (size == count)
                {
                    correct = true;
                    screenManager.AddScreen(new Clear(0));
                }
                state = State.Pause;
            }
            HandleInput(touch);
        }

        public void HandleInput(Touch touch)
        {
            foreach (GestureSample gesture in touch.Gestures)
            {
                if (gesture.GestureType == GestureType.FreeDrag)
                {
                    Point tapLocation = new Point((int)gesture.Position.X, (int)gesture.Position.Y);

                    if (!select)
                    {
                        for (int i = 0; i < size; i++)
                        {
                            if (tapLocation.X > shape[i].X &&
                            tapLocation.X < shape[i].X + piece[i].Width &&
                            tapLocation.Y > shape[i].Y &&
                            tapLocation.Y < shape[i].Y + piece[i].Height)
                            {
                                if (!IsRegionTransparent(piece[i], new Rectangle(tapLocation.X - shape[i].X, tapLocation.Y - shape[i].Y, 5, 5)))
                                {
                                    select = true;
                                    number = i;
                                    break;
                                }
                            }
                        }
                    }
                    if (select)
                    {
                       
                            shape[number].X += (int)gesture.Delta.X;
                            shape[number].Y += (int)gesture.Delta.Y;
                    
                    }
                }
                else if (gesture.GestureType == GestureType.DragComplete)
                {
                    state = State.Active;
                    select = false;
                }
            }
        }
        public override void Draw(SpriteBatch spriteBatch, GameTime gameTime)
        {
            spriteBatch.Draw(polygon, new Vector2(250, 90), Color.White);

            for (int i = 0; i < size; i++)
            {
                spriteBatch.Draw(piece[i], new Vector2(shape[i].X, shape[i].Y), Color.White);
            }
            if (select)
            {
                spriteBatch.Draw(piece[number], new Vector2(shape[number].X, shape[number].Y), Color.White);
            }
        }
         */
    }
}
